package in.abip.kazumi;

import in.abip.kazumi.mjpeg.MjpegDataInputStream;
import in.abip.kazumi.mjpeg.MjpegSurfaceView;

import java.io.IOException;
import java.util.LinkedList;
import java.util.Queue;

import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
import org.apache.http.HttpRequestInterceptor;
import org.apache.http.auth.AuthState;
import org.apache.http.auth.Credentials;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.protocol.ClientContext;
import org.apache.http.impl.auth.BasicScheme;
import org.apache.http.protocol.HttpContext;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;

public class MainActivity extends Activity {

	final Handler _updateUiHandler = new Handler();
	final Handler _refreshHandler = new Handler();
	protected Queue<String> _inputs = new LinkedList<String>();
	protected Queue<String> _outputs = new LinkedList<String>();
	private String _hardwareIp = "192.168.2.50";
	private Integer _hardwarePort = 6667;
	private TelnetClient _telnetClient = new TelnetClient();
	private MjpegSurfaceView _mjpeg;
	private boolean _busy = false;

	private Runnable _sending = new Runnable() {
		public void run() {
			send();
		}
	};

	final Runnable _updatingUi = new Runnable() {
		public void run() {
			_updateUi();
		}
	};

	final Runnable _refreshing = new Runnable() {
		public void run() {
			refresh();
			_refreshHandler.removeCallbacks(_refreshing);
			_refreshHandler.postDelayed(_refreshing, 3000);
		}
	};

	private void _updateUi() {
		TextView text = null;
		String data = "";
		String hc = "";
		int value = 0;
		while (!_inputs.isEmpty()) {
			data = _inputs.poll();
			try {
				hc = data.substring(0, 4);
				if (hc.equals("0101")) {
					text = (TextView) findViewById(R.id.electricity);
				} else if (hc.equals("0102")) {
					text = (TextView) findViewById(R.id.oil);
				} else if (hc.equals("0103")) {
					text = (TextView) findViewById(R.id.water);
				} else if (hc.equals("0104")) {
					text = (TextView) findViewById(R.id.current);
				} else {
					continue;
				}
				hc = data.substring(4, data.length());
				value = Integer.parseInt(hc);
				text.setText(Integer.toString(value));
			} catch (Exception e) {

			}
		}
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main_activity);
		_initVideo();
	}

	@Override
	protected void onResume() {
		super.onResume();
		_readSettings();
		_refreshHandler.removeCallbacks(_refreshing);
		_refreshHandler.postDelayed(_refreshing, 100);
	}

	@Override
	protected void onPause() {
		super.onPause();
		_refreshHandler.removeCallbacks(_refreshing);
		// _mjpeg.stopPlayback();
	}

	private void _initVideo() {
		HttpRequestInterceptor httpRequestInterceptor = null;
		httpRequestInterceptor = new HttpRequestInterceptor() {
			public void process(final HttpRequest request,
					final HttpContext context) throws HttpException,
					IOException {
				AuthState authState = (AuthState) context
						.getAttribute(ClientContext.TARGET_AUTH_STATE);

				if (authState.getAuthScheme() == null) {
					Credentials creds = new UsernamePasswordCredentials(
							"administrator", "abipadmin");
					authState.setAuthScheme(new BasicScheme());
					authState.setCredentials(creds);
				}
			}
		};

		StringBuilder url = new StringBuilder();
		// url.append("http://192.168.2.2:8080/");
		// url.append("cgi-bin/guest/Video.cgi?");
		// url.append("media=mjpeg&channel=1");
		// url.append("&sid=");
		// url.append(Double.toString(Math.random()));
		url.append("http://192.168.2.3/");
		url.append("nphMotionJpeg?Resolution=320x240&Quality=Standard");
		_mjpeg = (MjpegSurfaceView) findViewById(R.id.video);
		_mjpeg.setSource(MjpegDataInputStream.read(url.toString(),
				httpRequestInterceptor));
		_mjpeg.setDisplayMode(MjpegSurfaceView.SIZE_BEST_FIT);
		_mjpeg.showFps(false);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		getMenuInflater().inflate(R.menu.options, menu);
		menu.findItem(R.id.settings).setIntent(
				new Intent(this, SettingsActivity.class));
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		String menu = item.getTitle().toString();
		if (menu.equals(getString(R.string.settings))) {
			super.onOptionsItemSelected(item);
			startActivity(item.getIntent());
		}
		return true;
	}

	protected void refresh() {
		_outputs.add("ATS");
		startSend();
	}

	private void _readSettings() {
		SharedPreferences pref = getSharedPreferences(
				SettingsActivity.SETTINGS, Context.MODE_PRIVATE);
		if (pref.contains(SettingsActivity.HARDWARE_IP)) {
			_hardwareIp = pref.getString(SettingsActivity.HARDWARE_IP,
					"192.168.2.50");
		} else {
			_hardwareIp = "192.168.2.50";
		}
		if (pref.contains(SettingsActivity.HARDWARE_PORT)) {
			_hardwarePort = pref.getInt(SettingsActivity.HARDWARE_PORT, 6667);
		} else {
			_hardwarePort = 6667;
		}
	}

	protected void send() {
		String command = null;
		String result = null;

		_busy = true;
		if (_telnetClient.connect(_hardwareIp, _hardwarePort)) {
			while ((command = _outputs.poll()) != null) {
				result = _telnetClient.attention(command);
				if (result.length() > 0) {
					String[] list = result.split(",");
					String value = "";
					for (int i = 0; i < list.length; i++) {
						value = list[1].trim();
						if (value.length() >= 5) {
							_inputs.add(list[i].trim());
						}
					}
				}
			}
			_telnetClient.disconnect();
			_updateUiHandler.post(_updatingUi);
		} else {
			_outputs.clear();
		}
		_busy = false;
	}

	protected void startSend() {
		if (!_busy) {
			Thread thread = new Thread(null, _sending, "Sending");
			thread.start();
		}
	}

}